package obecto.task
{
	import flash.utils.setTimeout;
	
	import obecto.event.EventDescriptor;
	import obecto.event.TaskEvent;
	import obecto.utility.Listener;
	
	public class TaskInterruptibleWrapper extends BaseInterruptibleTask
	{
		protected var _wrappedTask : ITask;
		protected var completeListener : Listener;
		
		public function TaskInterruptibleWrapper(task : ITask)
		{
			super();
			
			wrappedTask = task;
		}
	
		override protected function startActual() : void
		{	
			if(wrappedTask == null)
			{
				setTimeout(complete, 5);
			}
			else
			{
				completeListener = Listener.createSingleTimeListener(new EventDescriptor(wrappedTask, TaskEvent.COMPLETE),
						handleWrappedTaskComplete, true);
										
				wrappedTask.start();				
			}
		}
		
		override public function end() : void
		{
			removeCompleteListener();
			super.end();
		}
		
		override public function interrupt() : void
		{
			removeCompleteListener();
			super.interrupt();
		}
		
		override public function reverse() : void
		{
			removeCompleteListener();
			super.reverse();
		}

		override public function rollback() : void
		{
			removeCompleteListener();
			super.rollback();
		}	
		
		protected function handleWrappedTaskComplete(event : TaskEvent) : void
		{
			removeCompleteListener();
			complete();
		}
		
		protected function removeCompleteListener() : void
		{
			if(completeListener != null)
			{
				if(completeListener.listening == true)
				{
					completeListener.stop();
				}
				
				completeListener = null;
			}
		}
		
		public function set wrappedTask(value : ITask) : void
		{
			if(_wrappedTask != value)
			{
				_wrappedTask = value;
				
				removeCompleteListener();
				
				if(running == true)
				{
					_running = false;
					start();
				}
			}
		}
		
		public function get wrappedTask() : ITask
		{
			return _wrappedTask;
		}
	}
}